package com.cactus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cactus.entity.User;
import com.cactus.service.AuthService;
import com.cactus.service.TUserService;
import com.cactus.utils.AjaxResult;
import com.cactus.utils.JsonResult;
import com.cactus.utils.PageResult;
import com.cactus.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: cactus
 * @CreateDate: 2023/9/14 11:52
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AuthService authService;


    @Autowired
    private TUserService tUserService;

    // 登录
    @PostMapping("/login")
    public AjaxResult createToken(@RequestParam String username, @RequestParam String userType) throws AuthenticationException {
        String token = authService.login(username);// 登录成功会返回JWT Token给用户
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("userType", userType);
        return AjaxResult.success(tokenMap);
    }

    // 注册
    @PostMapping("/register")
    public AjaxResult register(@RequestBody User addedUser) throws AuthenticationException {
        User createUser = SecurityUtils.getCurrentUsername();
        addedUser.setCreateBy(createUser.getUid());
        addedUser.setEndTime(createUser.getEndTime());
        authService.register(addedUser);
        return AjaxResult.success();
    }


    @PostMapping("/setUser")
    public AjaxResult setUser(@RequestBody User addedUser) {
        tUserService.updateById(addedUser);
        return AjaxResult.success();
    }


    @GetMapping
    public PageResult find(User addedUser) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<User>()
                .eq(addedUser.getStatus() != null, User::getStatus, addedUser.getStatus())
                .eq(addedUser.getUserType() != null, User::getUserType, addedUser.getUserType())
                .eq(addedUser.getUsername() != null, User::getUsername, addedUser.getUsername());

        List<User> list = tUserService.list(query);
        list.forEach(user -> user.setPassword(null));
        long total = tUserService.count(query);
        return new PageResult(total, list);
    }


    @GetMapping("/getById")
    public JsonResult getById() {
        String uid = SecurityUtils.getCurrentUsername().getUid();
        User user = tUserService.getById(uid);
        user.setPassword(null);
        return JsonResult.ok(user);
    }

}